<?php
/**
 * Created by PhpStorm.
 * User: zhan
 * Date: 2018/7/5  13:46
 */
namespace app\admin\controller;

class Contract extends Common
{
    private $table_admin;

    function __construct()
    {
        parent::__construct();
        $this->table_admin = db('contract');
    }

    /*
    合同列表
    */
    public function index()
    {
        $pageParam = ['query' =>[]];
        $where = [];
        $keyword = input('keyword');
        if( $keyword != ''){
            $where['title'] = array('like','%'.input('keyword').'%');
            $pageParam['query']['keyword'] = $keyword;
            $this->assign('keyword', $keyword);
        }

        $cid = input('cid');
        if($cid != ''){
            $where['cid'] = $cid;
            $pageParam['query']['cid'] = $cid;
        }
        $this->assign('cid', $cid);

        $article_result = $this->table_admin
            ->where($where)
            ->order('create_time desc')
            ->paginate(2, false, $pageParam);
//        halt($article_result);
        $page  = $article_result->render();
        $this->assign('page', $page);
        $this->assign('article_result', $article_result);

        return $this->fetch('Contract/list');
    }

    //添加合同
    public function add()
    {
        if(request()->isPost()){
            // $data = request()->param();
             $file = request()->file('photoname');
             halt($file);
            // halt($data);
            $id = input('id');

            $title = input('title');
            $number = input('number');
            $start_time = strtotime(input('start_time'));
            $finish_time =strtotime(input('finish_time'));
            $user = input('user');
            $company = input('company');
            $content = input('content');
            $mobile = input('mobile');

            $data['title'] = $title;
            $data['number'] = $number;
            $data['start_time'] = $start_time;
            $data['finish_time'] = $finish_time;
            $data['user'] = $user;
            $data['company'] = $company;
            $data['content'] = $content;
            $data['mobile'] = $mobile;
// halt($data);
            if(!$data['title']) $this->error("标题不能为空!");
            if(!$data['content']) $this->error("内容不能为空!");
//            if($data['finish_time']<time()){
//                $this->error("结束时间有误!");
//            }
            //合同照片上传
            $files = request()->file('photoname');
            $images=input('photo/a');
            foreach($files as $file){
                    // 移动到框架应用根目录/public/uploads/ 目录下
                    $info = $file->validate(['ext'=>'jpg,png,gif,jpeg,bmp'])->move(ROOT_PATH . 'public/static/uploads');
                    if($info){
                       if($images) {
                            array_push($images, $info->getSaveName());
                        }else{
                            $images[] = $info->getSaveName();
                        }
                        
                    }else{
                        // 上传失败获取错误信息
                        return $this->error($file->getError());
                    }    
                }
                if($images){
                $data['img']=serialize($images);
            }

//            文件上传
            $ht_file = request()->file('file');
            if($ht_file){
                $info = $ht_file->move(ROOT_PATH . 'public/static/uploads');
                if ($info) {
                    $file_path = $info->getSaveName();
                    $getInfo = $info->getInfo();
                    $data_file['file_name'] = $getInfo['name'];
                    $data_file['file_path'] = $file_path;
                    $data_file['file_time'] = time();
                    $file_suffix = substr(strrchr($file_path, '.'), 1);
                    $data_file['file_suffix'] = $file_suffix;
                    $data_file['file_size'] = $getInfo['size'];

                    db('file')->insert($data_file);
                    $file_id = db('file')->getLastInsID();
                    $data['file_id'] = $file_id;
                }else{
                    // 上传失败获取错误信息
                    return $this->error($file->getError());
                }

                //修改逻辑，修改附件，需删除原附件
                $did = input('file_id');
                if(!empty($did)){
                    $file_path = db('file')->where('id',$did)->value('file_path');
                    $fileurl = ROOT_PATH . 'public/static/uploads/'.$file_path;
                    $res = db('file')->where('id',$did)->delete();
                    if($res && file_exists($fileurl) && !empty($file_path)){
                        unlink($fileurl);
                    }
                }
            }

            if($id){
                //修改
                $bool = $this->table_admin->where('id='.$id)->update($data);
            }else{
                $data['create_time'] = time();
                //添加
                $bool = $this->table_admin->insert($data);
//                $sql = $this->table_admin->getLastSql();
//                $this->success($sql);exit;
            }
            if($bool){
                $this->success('操作成功', url('Contract/index'));
            }else{
                $this->error('操作失败');
            }
        }
        return $this->fetch();
    }

    //修改合同
    public function edit()
    {
        $id = input('id');
        $data = $this->table_admin->where('id='.$id)->find();
        $data['img'] = unserialize($data['img']);
        $this->assign('data', $data);
        return $this->fetch();
    }

    public function info()
    {
        $id = input('id');
        $data = $this->table_admin->where('id='.$id)->find();
        $data['img'] = unserialize($data['img']);
        if($data['file_id']){
            $file = db('file')->where(['id'=>$data['file_id']])->find();
            $data['file'] = $file;
        }
        $this->assign('data', $data);
        return $this->fetch();
    }

    //删除合同
    public function delete()
    {
        $id = input("id");
        if(!$id) $this->error('参数有误');
        $da=$this->table_admin->where("id='$id'")->find();
        if(!$da) $this->error('数据不存在');
        if(!empty($da['img'])){
            $img = unserialize($da['img']);
            foreach($img as $file){
                $pic = ROOT_PATH . 'public/static/uploads/'.$file;
                if(file_exists($pic)){
                    unlink($pic);
                }
            }
        }
        if(!empty($da['file_id'])){
            $fileurl = db('file')->where('id', $da['file_id'])->value('file_path');
            $file = ROOT_PATH . 'public/static/uploads/'.$fileurl;
            if(file_exists($file)){
                unlink($file);
            }
            $fileres = db('file')->where('id', $da['file_id'])->delete();
        }
        
        $res=$this->table_admin->where("id='$id'")->delete();
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!",url('Contract/index'));

    }

//    删除图片
    public function delImg()
    {
        $img = input('img');
        $id = input('id');
        if(!$img && !$id )$this->error('参数有误');
        $dataimg = $this->table_admin->where('id', $id)->value('img');
        $dataimg = unserialize($dataimg);
        $imgar = array(str_replace('/static/uploads/','',$img));
        $data['img'] = empty(array_diff($dataimg,$imgar))?'':serialize(array_diff($dataimg,$imgar));

        $file = ROOT_PATH . 'public' . $img;
        if(file_exists($file)){
            unlink($file);
            $res = $this->table_admin->where('id='.$id)->update($data);
        }else{
            $this->error('数据不存在！');
//            $this->error($file);
        }
        if(!$res) $this->error('删除失败');
        $this->success("删除成功!");
    }
}